//
//  Utilities.m
//  ios-loan
//
//  Created by ys on 15/12/2017.
//  Copyright © 2017 hxhg. All rights reserved.
//

#import "Utilities.h"
#import "MacroDefinition.h"
#import "ALLog.h"

@implementation Utilities
AL_DEF_SINGLETON(Utilities)
-(instancetype)init{
    self=[super init];
    if (self) {
        if ([GetGlobalApiByKey(@"ChannelType") isEqualToString:@"pgyer"]){
            self.isAppStore=YES;
            self.isAppStoreState=AppStoreStateTrue;
        }else{
            _isAppStore=YES; //默认
        }
    }
    return self;
}
+ (NSString *)appCode {
    __autoreleasing NSString *appVersion = [[[NSBundle mainBundle] infoDictionary]
                                            objectForKey:@"CFBundleShortVersionString"];
    if (!appVersion) {
        return @"";
    }
    NSString *resultStr= [appVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    return resultStr;
}

+ (NSString *)appVersion {
    __autoreleasing NSString *appVersion = [[[NSBundle mainBundle] infoDictionary]
                                          objectForKey:@"CFBundleShortVersionString"];
    if (!appVersion) {
        return @"";
    }
    return appVersion;
}

+ (NSString *)getValidatTimeKeyString {
    double da = [NSDate date].timeIntervalSince1970 * 1000;
    NSArray *numArr = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V"];
    NSMutableString *str = [NSMutableString string];
    while (da) {
        [str insertString:numArr[(unsigned long)da % 32] atIndex:0];
        da /= 32;
        if (da < 32) {
            [str insertString:numArr[(unsigned long)da] atIndex:0];
            break;
        }
    }
    if (!str.length) {
        LogE(@"getValidatTimeKeyString Error");
    }
    return str;
}

static uint8_t const kBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

+ (NSString *)encodeString:(NSString *)sourceString {
    NSData *data = [NSData dataWithBytes:[sourceString UTF8String] length:[sourceString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    return [self encodeData:data];
}

+ (NSString *)encodeData:(NSData *)data {
    NSUInteger length = [data length];
    NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    
    uint8_t *input = (uint8_t *)[data bytes];
    uint8_t *output = (uint8_t *)[mutableData mutableBytes];
    
    for (NSUInteger i = 0; i < length; i += 3) {
        NSUInteger value = 0;
        
        for (NSUInteger j = i; j < (i + 3); j++) {
            value <<= 8;
            
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        NSUInteger idx = (i / 3) * 4;
        output[idx + 0] = kBase64EncodingTable[(value >> 18) & 0x3F];
        output[idx + 1] = kBase64EncodingTable[(value >> 12) & 0x3F];
        output[idx + 2] = (i + 1) < length ? kBase64EncodingTable[(value >> 6) & 0x3F] : '=';
        output[idx + 3] = (i + 2) < length ? kBase64EncodingTable[(value >> 0) & 0x3F] : '=';
    }
    
    return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}

+ (NSString *)documentPath {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

+ (NSString *)cachePath {
    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
}

+ (NSArray<NSDictionary *> *)getCitysWithAdcodes:(NSArray<NSString *> *)adcodes {
    NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"]];
    NSError *error = nil;
    NSArray *citysArray = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:&error];
    if (!error) {
        NSMutableArray * tmp = [NSMutableArray array];
        for (NSDictionary * city in citysArray) {
            if ([adcodes containsObject:city[@"adcode"]]) {
                [tmp addObject:city];
            }
        }
        return tmp;
    }else {
        return nil;
    }
}
//+ (NSString *)hostUrlUtils{
//    NSString *hostPreName = GetApiByKey(@"curHostName");
//    return [Utilities commonSuf:hostPreName];
//}
//+ (NSString *)shareUrl{
//    NSString *sharePreName = GetApiByKey(@"curShareUrlName");
//    return [Utilities commonSuf:sharePreName];
//}
//+ (NSString *)questionUrl{
//    NSString *questionPreName = GetApiByKey(@"curQuestionUrlName");
//    return [Utilities commonSuf:questionPreName];
//}
//+ (NSString *)commonSuf:(NSString *)hostPreName{
//    //===================方便测试使用  如果有设置值，说明测试在使用包=======================================
//    id hosttype= [[NSUserDefaults standardUserDefaults] valueForKey:@"hosttype"];
//    NSString *hostName=nil;
//    if (hosttype) {
//        hostName= [hostPreName stringByAppendingString:hosttype];
//    }else{
//        hostName= [hostPreName stringByAppendingString:GetApiByKey(@"environment_suf")];
//    }
//    NSString *host= GetApiByKey(hostName);
//    return host;
//}
+ (NSString *)getApiByKey:(NSString *)key{
    //===================方便测试使用  如果有设置值，说明测试在使用包=======================================
    id hosttype= [[NSUserDefaults standardUserDefaults] valueForKey:@"hosttype"];
    if (hosttype) {
        if ([hosttype isEqualToString:@"pro"]) { //生产环境
            NSString *tempStr= [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ALConfigByEnvironment_pro" ofType:@"plist"]][key];
            return tempStr;
        }else if ([hosttype isEqualToString:@"dev"]){ //开发环境
            NSString *tempStr= [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ALConfigByEnvironment_dev" ofType:@"plist"]][key];
            return tempStr;
        }else if ([hosttype isEqualToString:@"qa"]){ //测试环境
            NSString *tempStr= [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ALConfigByEnvironment_qa" ofType:@"plist"]][key];
            return tempStr;
        }else{
            return @"";
        }
    }else{
        return @"";
    }
}
+ (NSString *)getChannelByKey:(NSString *)key{
    if ([GetGlobalApiByKey(@"ChannelType") isEqualToString:@"pgyer"]) { //蒲公英
        NSString *tempStr= [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ALConfigByChannel_pgyer" ofType:@"plist"]][key];
        return tempStr;
    }else if ([GetGlobalApiByKey(@"ChannelType") isEqualToString:@"appstore"]){ //appstore
        NSString *tempStr= [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ALConfigByChannel_appstore" ofType:@"plist"]][key];
        return tempStr;
    }else{
        return @"";
    }
}
- (void)hasAppStore:(void(^)(AppStoreState hasAppStore))backBlock{
//    WeakSelf
//    [UserNetworkService Options2:^(NSDictionary *options, NSError *error) {
//        if (!error) {
//            BOOL hasAppStore =[options[@"hasAppStore"] boolValue];
////            weakself.isAppStore=hasAppStore;
////            weakself.isAppStore=hasAppStore?AppStoreStateTrue:AppStoreStateFalus;
//
//            weakself.isAppStore=NO;
//            weakself.isAppStoreState=AppStoreStateFalus;
//        }else{
//            weakself.isAppStore=NO;
//            weakself.isAppStoreState=AppStoreStateNone;
//        }
//        backBlock(weakself.isAppStore);
//    }];
}

- (void)hasAppStore2:(id<AppStoreStateDelegate>)delegate{
//    WeakSelf
//    self.theStateDelegate=delegate;
//    [UserNetworkService Options2:^(NSDictionary *options, NSError *error) {
//        if (!error) {
//            BOOL hasAppStore =[options[@"hasAppStore"] boolValue];
//            weakself.isAppStore=hasAppStore;
//            weakself.isAppStore=hasAppStore?AppStoreStateTrue:AppStoreStateFalus;
//            
////            weakself.isAppStore=NO;
////            weakself.isAppStoreState=AppStoreStateFalus;
//        }else{
//            weakself.isAppStore=NO;
//            weakself.isAppStoreState=AppStoreStateNone;
//        }
//        if (self.theStateDelegate&&[self.theStateDelegate respondsToSelector:@selector(appStoreStateResult:)]) {
//            [self.theStateDelegate appStoreStateResult:weakself.isAppStoreState];
//        }
//    }];
}
@end
